package com.one.dao.impl;

import com.one.dao.cartDao;
import com.one.pojo.Cart;
import com.one.utils.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author LJ
 * @create 2022-04-25-16:34
 */
public class cartDaoImpl implements cartDao {
    @Override
    public boolean save(Cart cart) {
        try(Connection connection = DBUtils.getConnection();) {
            PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO cart(NAME,DATA,number,price,START,userid) VALUE(?,?,?,?,?,?)");
            preparedStatement.setString(1, cart.getName());
            preparedStatement.setString(2, cart.getData());
            preparedStatement.setInt(3, cart.getNumber());
            preparedStatement.setBigDecimal(4, cart.getPrice());
            preparedStatement.setInt(5, cart.getStart());
            preparedStatement.setInt(6, cart.getUserId());
            int update = preparedStatement.executeUpdate();
            if (update>0){
                return true;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return false;
}

    @Override
    public List<Cart> allCart() {
        List<Cart> list=new ArrayList();
        try (Connection connection = DBUtils.getConnection();){
            PreparedStatement preparedStatement = connection.prepareStatement("select NAME,DATA,number,price from cart");
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()){
                Cart cart=new Cart();
                cart.setPrice(resultSet.getBigDecimal("price"));
                cart.setNumber(resultSet.getInt("number"));
                cart.setName(resultSet.getString("NAME"));
                cart.setData(resultSet.getString("DATA"));
                list.add(cart);
            }

            return list;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }


        return list;
    }
}
